# PWA功能验证脚本
# 用于验证精英杂志PWA应用的各项功能

import os
import json
import sys

def check_file_exists(filepath, description):
    """检查文件是否存在"""
    if os.path.exists(filepath):
        print(f"✅ {description}: 存在")
        return True
    else:
        print(f"❌ {description}: 不存在")
        return False

def validate_manifest():
    """验证manifest.json配置"""
    try:
        with open('manifest.json', 'r', encoding='utf-8') as f:
            manifest = json.load(f)
        
        print("📋 Manifest配置验证:")
        
        # 检查必需字段
        required_fields = ['name', 'short_name', 'start_url', 'display', 'background_color', 'theme_color']
        for field in required_fields:
            if field in manifest:
                print(f"  ✅ {field}: {manifest[field]}")
            else:
                print(f"  ❌ {field}: 缺失")
        
        # 检查图标配置
        if 'icons' in manifest and len(manifest['icons']) > 0:
            print(f"  ✅ icons: 配置了 {len(manifest['icons'])} 个图标")
            for icon in manifest['icons']:
                icon_path = icon['src'].lstrip('/')
                if os.path.exists(icon_path):
                    print(f"    ✅ {icon['src']}: 存在 ({icon['sizes']})")
                else:
                    print(f"    ⚠️  {icon['src']}: 文件不存在")
        else:
            print("  ❌ icons: 未配置")
        
        # 检查截图配置
        if 'screenshots' in manifest:
            print(f"  ✅ screenshots: 配置了 {len(manifest['screenshots'])} 张截图")
        
        return True
        
    except Exception as e:
        print(f"❌ Manifest验证失败: {e}")
        return False

def validate_service_worker():
    """验证Service Worker文件"""
    print("\n🔧 Service Worker验证:")
    
    sw_file = 'service-worker.js'
    if not os.path.exists(sw_file):
        print("❌ service-worker.js: 文件不存在")
        return False
    
    try:
        with open(sw_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 检查关键功能
        checks = [
            ('install事件', 'install' in content),
            ('activate事件', 'activate' in content),
            ('fetch事件', 'fetch' in content),
            ('缓存策略', 'caches' in content),
            ('离线页面', 'offline.html' in content or 'offline' in content)
        ]
        
        for check_name, check_result in checks:
            if check_result:
                print(f"  ✅ {check_name}: 已配置")
            else:
                print(f"  ⚠️  {check_name}: 未找到")
        
        return True
        
    except Exception as e:
        print(f"❌ Service Worker验证失败: {e}")
        return False

def validate_pwa_files():
    """验证PWA相关文件"""
    print("\n📁 PWA文件验证:")
    
    files_to_check = [
        ('manifest.json', 'Web App Manifest'),
        ('service-worker.js', 'Service Worker脚本'),
        ('offline.html', '离线页面'),
        ('static/css/pwa-styles.css', 'PWA样式文件'),
        ('static/css/pwa-install.css', '安装提示样式'),
        ('static/css/mobile-optimization.css', '移动端优化样式'),
        ('static/js/pwa-installer.js', 'PWA安装管理器'),
        ('static/js/pwa-install.js', '安装提示脚本'),
        ('static/offline-test.html', '离线测试页面')
    ]
    
    all_exist = True
    for filepath, description in files_to_check:
        if not check_file_exists(filepath, description):
            all_exist = False
    
    return all_exist

def validate_html_integration():
    """验证HTML集成"""
    print("\n🌐 HTML集成验证:")
    
    try:
        # 检查主题模板
        baseof_path = 'themes/magazine-theme/layouts/_default/baseof.html'
        if os.path.exists(baseof_path):
            with open(baseof_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            checks = [
                ('viewport meta标签', 'viewport' in content),
                ('theme-color meta标签', 'theme-color' in content),
                ('apple-mobile-web-app标签', 'apple-mobile-web-app' in content),
                ('manifest链接', 'manifest.json' in content),
                ('PWA样式文件', 'pwa-styles.css' in content),
                ('移动端优化样式', 'mobile-optimization.css' in content),
                ('Service Worker脚本', 'pwa-installer.js' in content)
            ]
            
            for check_name, check_result in checks:
                if check_name == 'Service Worker脚本':
                    # 检查实际的Service Worker注册
                    if 'pwa-installer.js' in content and 'PWAInstallManager' in content:
                        print(f"  ✅ {check_name}: 已集成")
                    else:
                        print(f"  ⚠️  {check_name}: 未完全集成")
                else:
                    if check_result:
                        print(f"  ✅ {check_name}: 已集成")
                    else:
                        print(f"  ❌ {check_name}: 未集成")
        
        return True
        
    except Exception as e:
        print(f"❌ HTML集成验证失败: {e}")
        return False

def main():
    """主验证函数"""
    print("🚀 精英杂志PWA功能验证")
    print("=" * 50)
    
    # 确保在正确的目录
    if not os.path.exists('manifest.json'):
        print("❌ 请在magazine目录下运行此脚本")
        return False
    
    results = []
    
    # 执行各项验证
    results.append(validate_manifest())
    results.append(validate_service_worker())
    results.append(validate_pwa_files())
    results.append(validate_html_integration())
    
    print("\n" + "=" * 50)
    print("📊 验证总结:")
    
    if all(results):
        print("🎉 所有PWA功能验证通过!")
        print("\n🌟 功能特性:")
        print("  ✅ 完整的Web App Manifest配置")
        print("  ✅ Service Worker缓存策略")
        print("  ✅ PWA安装提示功能")
        print("  ✅ 移动端响应式设计")
        print("  ✅ 离线页面支持")
        print("  ✅ 深色模式适配")
        print("  ✅ 触摸优化")
        print("\n🚀 部署建议:")
        print("  1. 确保使用HTTPS协议")
        print("  2. 配置正确的服务器MIME类型")
        print("  3. 测试各种设备和浏览器")
        print("  4. 验证离线功能正常工作")
        return True
    else:
        print("⚠️  部分功能需要修复")
        print("请根据上面的验证结果进行相应的修复")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)